package com.zq.server.api.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zq.common.constant.TagConstant;
import com.zq.common.core.context.BaseContext;
import com.zq.common.enums.BusinessEnum;
import com.zq.common.exception.base.BaseException;
import com.zq.server.api.dao.TagMapper;
import com.zq.server.api.dao.UserTagMapper;
import com.zq.server.api.domain.entity.ApiTag;
import com.zq.server.api.domain.entity.ApiUserTag;
import com.zq.server.api.service.ApiTagService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Super
 * @description 针对表【tag】的数据库操作Service实现
 * @createDate 2024-03-04 00:39:16
 */
@Slf4j
@Service
public class ApiTagServiceImpl implements ApiTagService {
    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private UserTagMapper userTagMapper;

    /**
     * 添加标签
     *
     * @param tag
     */
    public void save(ApiTag tag) {
        //参数校验
        if (tag == null) {
            log.error("Tag cannot be null");
            throw new BaseException(TagConstant.TAG_PARAM_NULL);
        }
        try {
            tagMapper.save(tag);
        } catch (BaseException e) {
            log.error("Error occurred during tag save process: {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 添加标签
     *
     * @param paramArray 前端传来的标签数组
     * @return 操作结果
     */
    @Transactional(rollbackFor = BaseException.class)
    public Boolean saveListTag(int[] paramArray) {
        Long userId = BaseContext.getCurrentId();
        //把数据转换成数组
        if (paramArray == null || paramArray.length == 0) {
            log.error("参数错误：标签数组为空或超过最大允许长度");
            // 如果前端传递的标签数组为空，直接删除用户的所有标签
            Boolean deleteResult = userTagMapper.deleteAllTagsByUserId(userId);
            if (deleteResult) {
                return true;
            } else {
                log.error("删除用户所有标签失败");
                return false;
            }
        }
        // 查询用户已有的标签
        int[] existingTagIds = userTagMapper.getUserTagListByUserId(userId);
        //需要添加的标签集合
        List<Integer> newTagIds = getNewTagListAndDeleteTagList(paramArray, existingTagIds);
        //需要删除的标签集合
        List<Integer> cancelTagIds = getNewTagListAndDeleteTagList(existingTagIds, paramArray);
        // 执行批量插入新标签
        if (!newTagIds.isEmpty()) {
            List<ApiUserTag> newTags = createUserTags(userId, newTagIds);
            boolean insertSuccess = userTagMapper.saveListByTagId(newTags);
            if (!insertSuccess) {
                log.error("批量插入新标签失败");
                throw new BaseException(BusinessEnum.DB_UPDATE_ERROR);
            }
        }
        // 删除取消的标签
        if (!cancelTagIds.isEmpty()) {
            userTagMapper.deleteTagsByUserIdAndTagIds(userId, cancelTagIds);
        }
        // 更新主表相关标签的使用次数字段
        if (!newTagIds.isEmpty()) {
            tagMapper.updateTagUsageCount(newTagIds);
        }
        return true;
    }

    /**
     * 获取用户可用的标签
     *
     * @return
     */
    public List<ApiTag> getUserTaglist() {
        Long userId = BaseContext.getCurrentId();
        // 查询用户已有的标签
        int[] existingTagIds = userTagMapper.getUserTagListByUserId(userId);
        //查询系统已有标签
        int[] tagIdList = tagMapper.getTagIdList();
        //需要返回的数据
        List<Integer> cancelTagIds = getNewTagListAndDeleteTagList(tagIdList, existingTagIds);
        if (cancelTagIds.size() <= 0) {
            List<ApiTag> tagList = new ArrayList<>();
            return tagList;
        }
        return tagMapper.getUserNeedTagList(cancelTagIds);
    }

    /**
     * 根据参数获取新增和取消的标签列表
     *
     * @param paramOne 参数数组1
     * @param paramTwo 参数数组2
     * @return 新增和取消的标签列表
     */
    private List<Integer> getNewTagListAndDeleteTagList(int[] paramOne, int[] paramTwo) {
        List<Integer> requestDate = new ArrayList<>();
        for (int one : paramOne) {
            boolean exists = false;
            for (int two : paramTwo) {
                if (one == two) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                requestDate.add(one);
            }
        }
        return requestDate;
    }

    /**
     * 创建UserTag对象列表
     *
     * @param userId 用户ID
     * @param tagIds 标签ID列表
     * @return UserTag对象列表
     */
    private List<ApiUserTag> createUserTags(Long userId, List<Integer> tagIds) {
        List<ApiUserTag> userTags = new ArrayList<>();
        for (Integer tagId : tagIds) {
            ApiUserTag userTag = new ApiUserTag();
            userTag.setUserId(userId);
            userTag.setTagId(tagId);
            userTag.setAssociatedTime(LocalDateTime.now());
            userTags.add(userTag);
        }
        return userTags;
    }
}
